from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse, JsonResponse, FileResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.parsers import JSONParser
#from snippets.models import Snippet
#from snippets.serializers import SnippetSerializer
from rest_framework.decorators import api_view
from rest_framework.response import Response
from django.db.models import F,Q

#from snippets.models import Snippet
from snippets.models import UserInfo, ProjectType, Project, InvestmentAnalyse, InfoPage, InfoTranslateHistory, InfoFolder
#from snippets.serializers import SnippetSerializer
from snippets.serializers import ProjectTypeSerializer, ProjectAbstructSerializer
from rest_framework import generics
import requests

import os
import json
import time
import hashlib
import random

"""
登录并返回token
登录信息例如
{
    "address":"5GeMxhXb2hoeoNJuR3rCheAivjh1391y5GLLQK5drsicUAw5",
    "timestamp":1629007888000,
    "sign":"0xd64e357f02b7b1d7c4939f1ee518cc3d4c89fc32d9e0ef358100b559ed4ea8056820a454bfd8c0cd43fa6a090d4cd86d9d5da1f21cb1cbf8e6483168d9d4358f"
}
如果登录成功则返回结果与token
"""
@api_view(['POST'])
def login(request):
    if request.method == 'POST':
        print(request.body)
        res = requests.post(url="http://nodejs:3000/login",data=request.body)
        response = res.json()
        if response['result'] == True:
            #登录成功则生成随机数，写在token中
            address = json.loads(request.body)["address"]
            token = address+str(time.time())
            token = hashlib.sha1((token).encode('utf-8')).hexdigest()
            response['token'] = token
            addresses_list = UserInfo.objects.filter(address = address).all()
            if len(addresses_list) == 0:
                # 未登录过，创建用户
                user_info = UserInfo(address = address, name = address, token = token)
                user_info.save()
            else:
                # 登录过，修改token
                test1 = UserInfo.objects.get(address=address)
                test1.token = token
                test1.save()
        return Response(response)


@api_view(['POST'])
def test(request):
    if request.method == 'POST':
        print(request.META.get("HTTP_AAA"))
        #print(request.authorization)

        return Response({"aaa":"aaa"})


"""
获取所有的项目类型
"""
@api_view(['GET'])
def project_type_list(request):
    if request.method == 'GET':
        snippets = ProjectType.objects.all()
        serializer = ProjectTypeSerializer(snippets, many=True)
        return Response(serializer.data)

"""
获取某个项目类型下的项目摘要
project_type 项目类型
"""
@api_view(['GET'])
def project_abstruct_by_type(request, project_type):
    if request.method == 'GET':
        snippets = Project.objects.filter(project_type = project_type, is_publish = True).all()
        serializer = ProjectAbstructSerializer(snippets, many=True)
        return Response(serializer.data)

"""
获取最新的项目摘要
count 最大数量
"""
@api_view(['GET'])
def project_abstruct_by_new(request, count):
    if request.method == 'GET':
        snippets = Project.objects.filter(is_publish = True).all().order_by("-publish_time")[:count]
        serializer = ProjectAbstructSerializer(snippets, many=True)
        return Response(serializer.data)

"""
获取项目介绍文章内容
id 项目id
"""
@api_view(['GET'])
def project_intruduction_content(request, project_id):
    if request.method == 'GET':
        snippets = Project.objects.filter(pk = project_id).values_list("id", "name", "intruduction").first()
        return Response({
            "id": snippets[0],
            "name": snippets[1],
            "content": snippets[2]
        })

"""
获取项目团队文章内容
"""
@api_view(['GET'])
def project_team_content(request, project_id):
    if request.method == 'GET':
        snippets = Project.objects.filter(pk = project_id).values_list("id", "team").first()
        return Response({
            "id": snippets[0],
            "content": snippets[1]
        })

"""
获取所有投资分析文章摘要
"""
@api_view(['GET'])
def project_investment_analyse_by_project(request, project_id, one_page_count, page_index):
    if request.method == 'GET':
        result = InvestmentAnalyse.objects.filter(is_publish = True, project = project_id).all().order_by("-publish_time")
        rtn = []
        for item in result[one_page_count*(page_index-1): one_page_count*page_index]:
            rtn.append({
                "id": item.id,
                "title": item.title,
                "publish_time": item.publish_time,
                "author_id": item.author.id,
                "author_name": item.author.name
            })
        return Response(rtn)

"""
获取投资分析文章内容
"""
@api_view(['GET'])
def project_investment_analyse_content(request, investment_analyse_id):
    if request.method == 'GET':
        snippets = InvestmentAnalyse.objects.filter(pk = investment_analyse_id).values_list("id", 'title','icon','project','is_publish','publish_time','author','content').first()
        print(snippets)
        return Response({
            "id": snippets[0],
            'title': snippets[1],
            'icon': snippets[2],
            'project': snippets[3],
            'is_publish': snippets[4],
            'publish_time': snippets[5],
            'author': snippets[6],
            'content': snippets[7]
        })

"""
买入情报
"""
@api_view(['POST'])
def info_buy(request):
    if request.method == 'POST':
        param = json.loads(request.body)
        token = request.META.get("HTTP_TOKEN")
        user_id = UserInfo.objects.filter(token = token).first()
        info = InfoPage.objects.filter(pk = param["info_id"]).first() 
        tx_hash = param["tx_hash"]
        amount = param["amount"]
        if info.is_sell_limit == True and info.sell_count >= info.sell_limit_count:
            return HttpResponse(status = 503) 
        print(info.time_limit)
        time_now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        if info.is_time_limit == True and str(info.time_limit) < time_now:
            return HttpResponse(status = 503) 
        item = InfoTranslateHistory(user_id = user_id, info_id = info, txhash = tx_hash, amount = amount)
        info.sell_count += 1
        info.save()
        item.save()
        return Response({
            "result":0
        })

"""
获取所有公开情报
"""
@api_view(['GET'])
def info_abstruct_get(request, one_page_count, page_index, order_publish_time, status, project_id):
    if request.method == 'GET':
        # 权限判断
        if request.META.get("HTTP_TOKEN") == None:
            return HttpResponse(status = 503) 
        user_id = UserInfo.objects.filter(token = request.META.get("HTTP_TOKEN")).first()
        if user_id == None:
            return HttpResponse(status = 503) 
        result = InfoPage.objects.all()
        # 筛选状态
        if status == 0:# 无筛选 
            result = result.filter(is_publish = True)
        elif status == 1:# NFT情报
            result = result.filter(need_nft = True, is_publish = True)
        elif status == 2:# 已结束 
            time_now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
            result = (result.filter(is_sell_limit = True, sell_count__gte = F('sell_limit_count')) | \
                    result.filter(is_time_limit = True, time_limit__lte = time_now)).filter(is_publish = True)
        elif status == 3: # 出售中 
            time_now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
            result = (result.filter(is_sell_limit = True, sell_count__lt = F('sell_limit_count')) | \
                    result.filter(is_time_limit = True, time_limit__gt = time_now)).filter(~Q(price = 0)).filter(is_publish = True)
        elif status == 4: # 公开中
            result = result.filter(price = 0)
        elif status == 5: # 出售限制 
            result = result.filter(is_sell_limit = True)
        elif status == 6: #,时间限制
            result = result.filter(is_time_limit = True)
        else:
            return HttpResponse(status = 404)

        # 筛选项目
        if project_id != 0:
            result = result.filter(project = project_id)

        # 按发布时间排序
        if order_publish_time == 0:
            result = result.order_by('publish_time')
        else:
            result = result.order_by('-publish_time')

        rtn = {
            "count": len(result),
            "data": []
        }
        for item in result[one_page_count*(page_index-1): one_page_count*page_index]:
            rtn["data"].append({
                'id': item.id,
                'created': item.created,
                'title': item.title,
                'icon': str(item.icon),
                'project_id': item.project.id,
                'project_name': item.project.name,
                'is_publish': item.is_publish,
                'publish_time': item.publish_time,
                'author': item.author.id,
                'author_name': item.author.name,
                #'content': item.content,
                'price': item.price,
                'content_type': item.content_type,
                'need_nft': item.need_nft,
                'is_sell_limit': item.is_sell_limit,
                'sell_limit_count': item.sell_limit_count,
                'sell_count': item.sell_count,
                'is_time_limit': item.is_time_limit,
                'time_limit': item.time_limit,
                'user_bought': True if len(InfoTranslateHistory.objects.filter(info_id = item, user_id = user_id)) > 0 else False
            })
        print(rtn)
        return Response(rtn)

"""
获取单个情报
"""
@api_view(['GET'])
def info_content_get(request, info_id):
    if request.method == 'GET':
        # 权限判断
        if request.META.get("HTTP_TOKEN") == None:
            return HttpResponse(status = 503) 
        user_id = UserInfo.objects.filter(token = request.META.get("HTTP_TOKEN")).first()
        item = InfoPage.objects.filter(pk = info_id).first()
        user_bought = True if len(InfoTranslateHistory.objects.filter(info_id = item, user_id = user_id)) > 0 else False
        if item.price != 0 and user_bought == False:
            return HttpResponse(status = 503)  
        if item.need_nft: 
            res = requests.post(url="http://nodejs:3000/get_member_nft_count",data=json.dumps({
                "address": user_id.address
            }))
            response = res.json()
            print(response)
            if response['result'] != 0 or int(response['msg']) <= 0:
                return HttpResponse(status = 503)
        return Response({
            'id': item.id,
            'created': item.created,
            'title': item.title,
            'icon': str(item.icon),
            'project_id': item.project.id,
            'project_name': item.project.name,
            'is_publish': item.is_publish,
            'publish_time': item.publish_time,
            'author': item.author.id,
            'author_name': item.author.name,
            'content': item.content,
            'price': item.price,
            'content_type': item.content_type,
            'need_nft': item.need_nft,
            'is_sell_limit': item.is_sell_limit,
            'sell_limit_count': item.sell_limit_count,
            'sell_count': item.sell_count,
            'is_time_limit': item.is_time_limit,
            'time_limit': item.time_limit,
            'user_bought': user_bought
        })

@api_view(['POST'])
def info_image_update(request):
    if request.method == "POST":
        file = request.FILES.get("file", None)
        if file:
            # dir = os.path.join(os.path.join(BASE_DIR, 'static'),'profiles')
            # destination = open(os.path.join(dir, myFile.name),
            #                     'wb+')
            suffix = file.name.split('.')[-1]
            if suffix.lower() not in ["png", "jpg", "jpeg", "bmp"]: 
                return HttpResponse(status=503)
            file_path = 'rest_static/ueditor/info_page/'+file.name
            while os.access(file_path, os.F_OK):
                file_path = 'rest_static/ueditor/info_page/' + time.strftime("%Y_%m_%d_%H_%M_%S", time.localtime()) +str(random.randint(1, 1000)) + "_" + file.name 
            file_to_write = open(file_path, "wb+")
            for chunk in file.chunks():
                file_to_write.write(chunk)
            file_to_write.close()
        return Response({
            "file_name": "/"+file_path
        })
    return HttpResponse(status=404)

@api_view(['POST'])
def info_page_icon_upload(request):
    if request.method == "POST":
        file = request.FILES.get("file", None)
        if file:
            suffix = file.name.split('.')[-1]
            if suffix.lower() not in ["png", "jpg", "jpeg", "bmp"]: 
                return HttpResponse(status=503)
            file_path = 'rest_static/info_page/'+file.name
            while os.access(file_path, os.F_OK):
                file_path = 'rest_static/info_page/' + time.strftime("%Y_%m_%d_%H_%M_%S", time.localtime()) +str(random.randint(1, 1000)) + "_" + file.name 
            file_to_write = open(file_path, "wb+")
            for chunk in file.chunks():
                file_to_write.write(chunk)
            file_to_write.close()
        return Response({
            "file_name": "/"+file_path
        })
    return HttpResponse(status=404)

"""
创建情报文件夹
"""
@api_view(['POST'])
def info_folder_create(request):
    if request.method == 'POST':
        param = json.loads(request.body)
        token = request.META.get("HTTP_TOKEN")
        user_id = UserInfo.objects.filter(token = token).first()
        folder_name = param["folder_name"]
        if user_id == None:
            return HttpResponse(status=503)

        info = InfoFolder(user_id = user_id, folder_name = folder_name)
        info.save()
        return Response({
            "result":0
        })

"""
获取情报文件夹
"""
@api_view(['GET'])
def info_folder(request):
    if request.method == 'GET':
        token = request.META.get("HTTP_TOKEN")
        user_id = UserInfo.objects.filter(token = token).first()
        info_folders = InfoFolder.objects.filter(user_id = user_id).values_list("id", 'folder_name','created')
        rtn = []
        for item in info_folders:
            rtn.append({
                "id": item[0],
                "folder_name": item[1],
                "created": item[2]
            })
        return Response(rtn)
    else:
        return HttpResponse(status=404)


@api_view(['POST'])
def info_publish(request):
    if request.method == 'POST':
        param = json.loads(request.body)
        token = request.META.get("HTTP_TOKEN")
        user_id = UserInfo.objects.filter(token = token).first()
        if user_id == None:
            return HttpResponse(status=503)
        info = InfoPage(
            title = param['title'],
            icon = param['icon'],
            info_folder = InfoFolder.objects.filter(pk=param["info_folder"]).first(),
            project = Project.objects.filter(pk=param['project']).first(),
            is_publish = param['is_publish'],
            publish_time = param['publish_time'],
            author = user_id,
            content = param['content'],
            price = param['price'],
            content_type = param['content_type'],
            need_nft = param['need_nft'],
            is_sell_limit = param['is_sell_limit'],
            sell_limit_count = param['sell_limit_count'],
            sell_count = param['sell_count'],
            is_time_limit = param['is_time_limit'],
            time_limit = param['time_limit']
        )
        info.save()
        return Response({
            "result":0
        })

"""
获取收款地址
"""
@api_view(['GET'])
def official_address(request):
    if request.method == 'GET':
        return Response({"address":"5GeMxhXb2hoeoNJuR3rCheAivjh1391y5GLLQK5drsicUAw5"})
    else:
        return HttpResponse(status=404)




@csrf_exempt
def project_image(request, name):
    if request.method == "GET":
        suffix = name.split('.')
        return FileResponse(open('rest_static/project_image/' + name,'rb'), content_type='image/'+suffix[-1])
    return HttpResponse(status=404)

@csrf_exempt 
def project_intruduction(request, name):
    if request.method == "GET":
        suffix = name.split('.')
        return FileResponse(open('rest_static/project_intruduction/' + name,'rb'), content_type='image/'+suffix[-1])
    return HttpResponse(status=404)

@csrf_exempt
def project_intruduction_ueditor(request, name):
    if request.method == "GET":
        suffix = name.split('.')
        return FileResponse(open('rest_static/ueditor/project_intruduction/' + name,'rb'), content_type='image/'+suffix[-1])
    return HttpResponse(status=404)

@csrf_exempt
def project_investment_analyse(request, name):
    if request.method == "GET":
        suffix = name.split('.')
        return FileResponse(open('rest_static/ueditor/project_investment_analyse/' + name,'rb'), content_type='image/'+suffix[-1])
    return HttpResponse(status=404)

@csrf_exempt
def project_team(request, name):
    if request.method == "GET":
        suffix = name.split('.')
        return FileResponse(open('rest_static/ueditor/project_team/' + name,'rb'), content_type='image/'+suffix[-1])
    return HttpResponse(status=404)

@csrf_exempt
def info_page(request, name):
    if request.method == "GET":
        suffix = name.split('.')
        return FileResponse(open('rest_static/info_page/' + name,'rb'), content_type='image/'+suffix[-1])
    return HttpResponse(status=404)

@csrf_exempt
def info_page_ueditor(request, name):
    if request.method == "GET":
        suffix = name.split('.')
        return FileResponse(open('rest_static/ueditor/info_page/' + name,'rb'), content_type='image/'+suffix[-1])
    return HttpResponse(status=404)


